package com.sardine.base.hbase.session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

import static com.sardine.base.hbase.session.HBaseSessionUtils.getHSession;

/**
 * 上海京东到家元信信息技术有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/11/21
 * Time:14:04
 *
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class HBaseSessionTemplate implements InitializingBean, HBaseSession {
    private static final Logger logger = LoggerFactory.getLogger(HBaseSessionTemplate.class);

    private HBaseSessionFactory sessionFactory;
    private HBaseSession sessionProxy;

    public void setSessionFactory(HBaseSessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.sessionProxy = getHSession(sessionFactory);
//        this.sessionProxy = (HBaseSession) Proxy.newProxyInstance(HBaseSessionFactory.class.getClassLoader(),new Class[]{HBaseSession.class},new HSessionInterceptor());
    }

    /**
     * 插入一条记录
     *
     * @param t
     * @return
     */
    @Override
    public boolean insert(Object t) {
        return sessionProxy.insert(t);
    }

    /**
     * 同步插入一组数据
     *
     * @param t
     * @return
     */
    @Override
    public boolean insert(List<? extends Object> t) {
        return sessionProxy.insert(t);
    }

    /**
     * 异步插入一组数据
     *
     * @param t
     * @return
     */
    @Override
    public boolean insertAsync(List<? extends Object> t) {
        return sessionProxy.insertAsync(t);
    }

    /**
     * 查询一条记录rowKey
     *
     * @param rowKey
     * @param aClass
     * @return
     */
    @Override
    public <T> T selectOne(Serializable rowKey, Class<T> aClass) {
        return sessionProxy.selectOne(rowKey, aClass);
    }

    /**
     * 批量查询一组rowkey
     *
     * @param rowKeyList
     * @param aClass
     * @return
     */
    @Override
    public <T> List<T> selectList(List<? extends Serializable> rowKeyList, Class<T> aClass) {
        return sessionProxy.selectList(rowKeyList,aClass);
    }

    private class HSessionInterceptor implements InvocationHandler {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            final HBaseSession session = getHSession(sessionFactory);
            try {
                Object result = method.invoke(session, args);
                return result;
            } catch (Throwable e) {
                throw new Throwable(e);
            } finally {
                logger.info("执行别的操作...");
            }
        }
    }
}
